package com.cqvip.innocence.framework.config.handler;

import com.cqvip.innocence.project.model.dto.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;

/**
 * 参数校验异常handler
 *
 * @author 01
 * @date 2022-07-27 11:16
 * @see {https://docs.spring.io/spring-boot/docs/2.7.2/reference/htmlsingle/#io.validation}
 */
@ControllerAdvice
public class ValidationExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult constraintViolationException(ConstraintViolationException ex, ServletRequest request, ServletResponse response) throws IOException {
        return JsonResult.Get(false, StringUtils.isNotBlank(ex.getMessage()) ? ex.getMessage().split(":")[1] : ex.getMessage());
    }
}
